<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit } from '@element-plus/icons-vue'
import { api } from '@/utils/request'
import type { Ticket } from '@/types/train'

const tickets = ref<Ticket[]>([])
const loading = ref(false)
const searchForm = ref({
  trainNumber: '',
  passengerName: '',
  status: ''
})

const statusOptions = [
  { label: '有效', value: 'VALID' },
  { label: '已使用', value: 'USED' },
  { label: '已取消', value: 'CANCELLED' },
  { label: '已退款', value: 'REFUNDED' }
]

const statusTypeMap: Record<string, string> = {
  VALID: 'success',
  USED: 'info',
  CANCELLED: 'warning',
  REFUNDED: 'danger'
}

// 获取票务列表
const fetchTickets = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams()
    if (searchForm.value.trainNumber) {
      params.append('trainNumber', searchForm.value.trainNumber)
    }
    if (searchForm.value.passengerName) {
      params.append('passengerName', searchForm.value.passengerName)
    }
    if (searchForm.value.status) {
      params.append('status', searchForm.value.status)
    }

    const response = await api.get<{ success: boolean; data: Ticket[] }>(`/tickets?${params.toString()}`)
    if (response.success) {
      tickets.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取票务列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索票务
const handleSearch = () => {
  fetchTickets()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    trainNumber: '',
    passengerName: '',
    status: ''
  }
  fetchTickets()
}

// 取消票务
const handleCancelTicket = async (ticket: Ticket) => {
  if (ticket.ticketStatus === 'CANCELLED' || ticket.ticketStatus === 'REFUNDED') {
    ElMessage.warning('该票务已取消或已退款')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要取消票务 ${ticket.id} 吗？此操作不可撤销。`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await api.put<{ success: boolean; message: string }>(`/tickets/${ticket.id}/cancel`)
    if (response.success) {
      ElMessage.success('票务取消成功')
      fetchTickets()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消票务失败')
      console.error(error)
    }
  }
}

// 删除票务（硬删除，谨慎操作）
const handleDeleteTicket = async (ticket: Ticket) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除票务 ${ticket.id} 吗？此操作将永久删除数据，无法恢复！`,
      '危险操作',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error',
        confirmButtonClass: 'el-button--danger'
      }
    )

    const response = await api.delete<{ success: boolean; message: string }>(`/tickets/${ticket.id}`)
    if (response.success) {
      ElMessage.success('票务删除成功')
      fetchTickets()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除票务失败')
      console.error(error)
    }
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  return new Date(dateTimeStr).toLocaleString('zh-CN')
}

// 格式化价格
const formatPrice = (price: number) => {
  return `¥${price.toFixed(2)}`
}

onMounted(() => {
  fetchTickets()
})
</script>

<template>
  <div class="ticket-management">
    <div class="header">
      <h2>票务管理</h2>
      <p>管理所有票务记录，包括查看、取消和删除操作</p>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="车次号">
          <el-input v-model="searchForm.trainNumber" placeholder="请输入车次号" clearable />
        </el-form-item>
        <el-form-item label="乘客姓名">
          <el-input v-model="searchForm.passengerName" placeholder="请输入乘客姓名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable filterable>
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 票务列表 -->
    <el-card>
      <template #header>
        <span>票务列表 ({{ tickets.length }})</span>
      </template>

      <el-table :data="tickets" v-loading="loading" stripe>
        <el-table-column prop="id" label="票务ID" width="80" />
        <el-table-column prop="trainNumber" label="车次号" width="100" />
        <el-table-column prop="passengerName" label="乘客姓名" width="120" />
        <el-table-column prop="passengerIdCard" label="身份证号" width="180" />
        <el-table-column label="出发-到达" width="200">
          <template #default="{ row }">
            <span>{{ row.startStationName }} → {{ row.endStationName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出发时间" width="150">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.departureTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="到达时间" width="150">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.arrivalTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="seatNumber" label="座位号" width="80" />
        <el-table-column label="价格" width="100">
          <template #default="{ row }">
            <span>{{ formatPrice(row.ticketPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTypeMap[row.ticketStatus]">
              {{ statusOptions.find(opt => opt.value === row.ticketStatus)?.label || row.ticketStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="150">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="warning"
              :icon="Edit"
              @click="handleCancelTicket(row)"
              :disabled="row.ticketStatus === 'CANCELLED' || row.ticketStatus === 'REFUNDED'"
            >
              取消
            </el-button>
            <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="handleDeleteTicket(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="tickets.length === 0 && !loading" class="empty-state">
        <p>暂无票务记录</p>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.ticket-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #909399;
}
</style>